﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Activities;
using System.Activities.Expressions;
using System.Activities.Presentation.PropertyEditing;
using System.Activities.Statements;
using System.Collections.Generic;
using System.ComponentModel;
using Core = Vision.Core;
using System.Windows.Markup;

namespace Vision.Core.ActivityComponents.IO.File
{
    /// <summary>
    /// 
    /// </summary>
	[ContentProperty("Body")]
	[System.ComponentModel.Designer(typeof(DirectoryListDesigner))]
    public class DirectoryList : NativeActivity
    {
        /// <summary>
        /// 
        /// </summary>
        [Category("Input")]
        [DefaultValue("")]
        public InArgument<string> DirectoryPath { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Category("Input")]
        [DefaultValue("")]
        public InArgument<string> SearchPattern { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Category("Input")]
        [DefaultValue(false)]
        public InArgument<bool> IncludeSubDirectories { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Category("Output")]
        public OutArgument<string[]> Directories { get; set; }

		/// <summary>
		/// 
		/// </summary>
		[Browsable(false)]
		[DefaultValue(null)]
		public ActivityAction<System.IO.DirectoryInfo[]> Body { get; set; }

		/// <summary>
        /// 
        /// </summary>
		public DirectoryList()
			: base()
        {
			this.IncludeSubDirectories = false;

			this.Body = new ActivityAction<System.IO.DirectoryInfo[]>()
			{
				Argument = new DelegateInArgument<System.IO.DirectoryInfo[]>() { Name = "dirInfoArray" }
            };
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(NativeActivityContext context)
        {
            List<string> dirList = new List<string>();            
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(this.DirectoryPath.Get(context));

            System.IO.DirectoryInfo[] diList = di.GetDirectories();
            if (this.SearchPattern.Get(context) != null){
                SearchOption so = SearchOption.TopDirectoryOnly;
                if (this.IncludeSubDirectories.Get(context) == true){
                    so = SearchOption.AllDirectories;
                }
                diList = di.GetDirectories(this.SearchPattern.Get(context), so);
            }

            foreach(var dir in diList){
                dirList.Add(dir.FullName);
            }
            
            this.Directories.Set(context, dirList.ToArray());

			// schedule the next action
			if (this.Body != null && this.Body.Handler != null)
			{
				context.ScheduleAction(this.Body, diList);
			}

            di = null;
        }
    }
}
